<template>
  <div ref="mouseTip" class="mouseTipClass" :style="mouseTipStyle">
    <slot></slot>
  </div>
</template>
<script>
export default {
  name: 'MouseTip',
  data() {
    return {
      visible: false,
      mouseTipStyle: {}
    }
  },
  mounted() {
    // 监听鼠标在浏览器可见区域中移动
    window.addEventListener('mousemove', this.mousemove)
    // 监听鼠标移出浏览器可见区域
    window.addEventListener('mouseout', this.mouseout)
  },
  methods: {
    setVisible(visible) {
      this.visible = visible
      if (this.visible) {
        this.$set(this.mouseTipStyle, 'display', 'block')
      } else {
        this.$set(this.mouseTipStyle, 'display', 'none')
      }
    },
    mouseout() {
      if (this.visible) {
        this.$set(this.mouseTipStyle, 'display', 'none')
      }
    },
    mousemove(e) {
      if (this.visible) {
        this.$set(this.mouseTipStyle, 'display', 'block')
        // 获取信息框的宽度
        let mouseTipWidth = window.getComputedStyle(this.$refs.mouseTip).width
        // 获取信息框的高度
        let mouseTipHeight = window.getComputedStyle(this.$refs.mouseTip).height
        // 当鼠标上方容不下信息框时，信息框改在鼠标下方显示
        if (e.clientY < Number(mouseTipHeight.replace('px', '')) + 20) {
          this.$set(this.mouseTipStyle, 'top', e.clientY + 20 + 'px')
        } else {
          this.$set(this.mouseTipStyle, 'top', e.clientY - 36 + 'px')
        }
        // 当鼠标右侧容不下信息框时，信息框改在鼠标左边显示
        if (e.clientX > document.documentElement.clientWidth - Number(mouseTipWidth.replace('px', ''))) {
          this.$set(this.mouseTipStyle, 'left', e.clientX - Number(mouseTipWidth.replace('px', '')) + 'px')
        } else {
          this.$set(this.mouseTipStyle, 'left', e.clientX + 'px')
        }
      }
    },
  }
}
</script>
<style scoped>
.mouseTipClass {
  display: none;
  position: fixed;
  z-index: 9999;
  background: #5e72af;
  border: 1px solid gray;
  padding: 4px 8px;
  border-radius: 4px;
  color: #FFFFFF;
  font-size: 14px;
}
</style>
